import random
import time
import json
from paho.mqtt import client as mqtt_client


# 77环境
broker = '192.168.141.77'
port = 1884
topic = "tlink/c32q6dqCd/S_FF_LD3/command/setProperty/exec"
# generate client ID with pub prefix randomly
client_id = f'testcjm|signmethod=hmacmd5|{random.randint(0, 1000)}'

# 116环境
# broker = '116.205.232.249'
# port = 10015
# topic = "tlink/c32q6dqCd/S_FF_LD3/command/setProperty/exec"
# # generate client ID with pub prefix randomly
# client_id = f'testcjm|signmethod=hmacmd5|{random.randint(0, 1000)}'


def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.username_pw_set("admin&admin", "bc219bd32010b7848139d1b131f71585")
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
        current_timestamp = time.time()
        payload={
            "reqid":"A8AA4E0A856382BF8CF24A53DA39C292",
            "v":1,
            "t":int(round(current_timestamp * 1000)),
            "method":"event.propertyReport.post",
            "spec":{"ack":0},
            "data":{"Err":{"value":1}}
        }
        # 将 payload 转换为字符串
        payload_str = json.dumps(payload)
        # 发布消息到另一个主题
        client.publish("tlink/c32q6dqCd/S_FF_LD3/event/propertyReport/post", payload_str)
        print(f"Published {payload} to `tlink/c32q6dqCd/S_FF_LD3/event/propertyReport/post` topic")
    client.subscribe(topic)
    client.on_message = on_message


def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()


if __name__ == '__main__':
    run()